// pages/workplace/workplace.ts
import { ShopAPI, MerchantAPI } from '../../utils/api'

interface WorkplaceData {
  userInfo: any;
  hasLogin: boolean;
  businessStatus: number;
  statusText: string;
  acceptOrderMode: string;
  modeText: string;
  orderStats: {
    todayOrders: number;
    yesterdayOrders: number;
    growthRate: number;
    trend: string;
  };
  revenueStats: {
    todayRevenue: number;
    yesterdayRevenue: number;
    growthRate: number;
    trend: string;
  };
  salesTrend: {
    period: string;
    data: Array<{ time: string; orders: number; revenue: number; }>;
  };
  quickActions: Array<{
    id: string;
    name: string;
    icon: string;
    badge: number;
    badgeText: string;
  }>;
  pendingTasks: {
    pendingOrders: number;
    pendingReviews: number;
    pendingComplaints: number;
  };
  statusBarHeight: number;
  navBarHeight: number;
}

Page({
  data: {
    userInfo: null,
    hasLogin: false,
    businessStatus: 0, // 0-营业中, 1-休息中, 2-暂停营业
    statusText: '营业中',
    acceptOrderMode: 'auto', // auto-自动接单, manual-手动接单
    modeText: '自动接单',
    orderStats: {
      todayOrders: 0,
      yesterdayOrders: 0,
      growthRate: 0,
      trend: 'up'
    },
    revenueStats: {
      todayRevenue: 0,
      yesterdayRevenue: 0,
      growthRate: 0,
      trend: 'up'
    },
    salesTrend: {
      period: 'today',
      data: []
    },
    quickActions: [],
    pendingTasks: {
      pendingOrders: 0,
      pendingReviews: 0,
      pendingComplaints: 0
    },
    statusBarHeight: 0,
    navBarHeight: 0
  } as WorkplaceData,

  onLoad() {
    const systemInfo = wx.getSystemInfoSync();
    const statusBarHeight = systemInfo.statusBarHeight || 0;
    const navBarHeight = statusBarHeight + 44;
    
    this.setData({
      statusBarHeight,
      navBarHeight
    });
    
    this.checkLoginStatus();
  },

  onShow() {
    this.checkLoginStatus();
    if (this.data.hasLogin) {
      // 从缓存加载商家信息，确保状态一致
      const userInfo = wx.getStorageSync('merchantUserInfo');
      if (userInfo) {
        const businessStatus = userInfo.canOperate ? 0 : 1;
        const statusText = userInfo.statusText || (businessStatus === 0 ? '营业中' : '休息中');
        
        this.setData({
          userInfo: userInfo,
          businessStatus: businessStatus,
          statusText: statusText
        });
      }
      
      this.loadWorkbenchData();
    }
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('merchantToken');
    const userInfo = wx.getStorageSync('merchantUserInfo');
    
    if (token && userInfo) {
      this.setData({
        hasLogin: true,
        userInfo
      });
    } else {
      this.setData({
        hasLogin: false,
        userInfo: null
      });
    }
  },

  // 模拟登录
  mockLogin() {
    const mockUserInfo = {
      merchantId: 1001,
      merchantName: '绿意轻食',
      contactPerson: '张经理',
      contactPhone: '138****8000',
      status: 1
    };
    
    wx.setStorageSync('merchantToken', 'mock_token_123456');
    wx.setStorageSync('merchantUserInfo', mockUserInfo);
    
    this.setData({
      hasLogin: true,
      userInfo: mockUserInfo
    });
    
    wx.showToast({
      title: '登录成功',
      icon: 'success'
    });
    
    this.loadWorkbenchData();
  },

  // 加载工作台数据
  async loadWorkbenchData() {
    try {
      // 调用真实的订单统计接口
      const [orderStats, todaySummary] = await Promise.all([
        MerchantAPI.getOrderStatistics(),
        MerchantAPI.getTodayOrderSummary()
      ]);
      
      console.log('订单统计数据:', orderStats);
      console.log('今日订单概览:', todaySummary);
      
      // 处理订单统计数据
      if (todaySummary && todaySummary.data) {
        const data = todaySummary.data;
        const todayOrders = data.orderCount || 0;
        const todayRevenue = data.totalAmount || 0;
        const pendingOrders = data.pendingCount || 0;
        
        this.setData({
          orderStats: {
            todayOrders: todayOrders,
            yesterdayOrders: data.yesterdayOrderCount || 0,
            growthRate: data.orderGrowthRate || 0,
            trend: data.orderGrowthRate >= 0 ? "up" : "down"
          },
          revenueStats: {
            todayRevenue: todayRevenue,
            yesterdayRevenue: data.yesterdayTotalAmount || 0,
            growthRate: data.revenueGrowthRate || 0,
            trend: data.revenueGrowthRate >= 0 ? "up" : "down"
          },
          'pendingTasks.pendingOrders': pendingOrders
        });
      }
      
      // 保留销售趋势和快捷操作的模拟数据
      this.setData({
        salesTrend: {
          period: "today",
          data: [
            {"time": "09:00", "orders": 5, "revenue": 580.00},
            {"time": "10:00", "orders": 8, "revenue": 920.00},
            {"time": "11:00", "orders": 12, "revenue": 1420.00},
            {"time": "12:00", "orders": 15, "revenue": 1780.00},
            {"time": "13:00", "orders": 8, "revenue": 950.00}
          ]
        },
        quickActions: [
          {
            id: "store_management",
            name: "门店管理",
            icon: "settings",
            badge: 0,
            badgeText: ''
          },
          {
            id: "announcement_management", 
            name: "公告管理",
            icon: "notice",
            badge: 0,
            badgeText: ''
          },
          {
            id: "product_management",
            name: "商品管理", 
            icon: "burger",
            badge: 0,
            badgeText: ''
          },
          {
            id: "combo_management",
            name: "套餐管理",
            icon: "burger",
            badge: 0,
            badgeText: ''
          },
          {
            id: "review_management",
            name: "评价管理",
            icon: "star-filled",
            badge: 0,
            badgeText: ''
          },
          {
            id: "custom_management",
            name: "定制管理", 
            icon: "note",
            badge: 0,
            badgeText: ''
          },
          {
            id: "activity_management",
            name: "店铺活动",
            icon: "notification",
            badge: 0,
            badgeText: ''
          },
          {
            id: "region_bindings",
            name: "区域绑定",
            icon: "location",
            badge: 0,
            badgeText: ''
          }
        ]
      });
      
      // 加载各个模块的徽章数据
      await this.loadBadgeCounts();
      
    } catch (error) {
      console.error('加载工作台数据失败:', error);
      wx.showToast({
        title: '数据加载失败',
        icon: 'none'
      });
    }
  },

  // 加载徽章数量
  async loadBadgeCounts() {
    try {
      // 1. 获取草稿公告数量
      await this.loadAnnouncementBadge();
      
      // 2. 其他徽章可以类似方式加载
      // await this.loadReviewBadge();
      // await this.loadCustomBadge();
      // await this.loadActivityBadge();
      
    } catch (error) {
      console.error('加载徽章数量失败:', error);
    }
  },

  // 加载公告徽章（已发布的公告数量）
  async loadAnnouncementBadge() {
    try {
      const MerchantAPI = require('../../utils/api').MerchantAPI;
      
      // 调用公告列表API，查询已发布状态
      const response = await MerchantAPI.getAnnouncementList({
        pageNum: 1,
        pageSize: 999, // 获取所有已发布的公告
        status: 1  // 1=已发布
      });
      
      if (response && response.code === 200) {
        const publishedCount = response.total || 0;
        
        // 更新公告管理的徽章
        const quickActions = this.data.quickActions.map((action: any) => {
          if (action.id === 'announcement_management') {
            return {
              ...action,
              badge: publishedCount,
              badgeText: this.formatBadgeText(publishedCount)
            };
          }
          return action;
        });
        
        this.setData({ quickActions });
      }
    } catch (error) {
      console.error('获取公告徽章失败:', error);
    }
  },

  // 格式化徽章文本（超过10显示10+）
  formatBadgeText(count: number): string {
    if (count > 10) {
      return '10+';
    }
    return count.toString();
  },

  /**
   * 切换营业状态（统一使用商家信息API）
   * @param {Object} e 事件对象
   */
  async toggleBusinessStatus(e: any) {
    const MerchantAPI = require('../../utils/api').MerchantAPI;
    const userInfo = this.data.userInfo || {};
    
    // 检查商家是否被封禁
    const statusNum = typeof userInfo.status === 'string' ? parseInt(userInfo.status) : userInfo.status;
    if (statusNum === 2) {
      wx.showToast({
        title: '商家已被封禁，无法切换状态',
        icon: 'none',
        duration: 2000
      });
      // 恢复开关状态
      this.setData({
        businessStatus: this.data.businessStatus === 0 ? 0 : 1
      });
      return;
    }

    // 检查审核状态
    if (userInfo.auditStatus !== 'APPROVED') {
      wx.showToast({
        title: '请先通过商家审核',
        icon: 'none',
        duration: 2000
      });
      // 恢复开关状态
      this.setData({
        businessStatus: this.data.businessStatus === 0 ? 0 : 1
      });
      return;
    }

    // 从switch的change事件获取目标状态
    // e.detail.value: true=营业中(0), false=休息中(1)
    const targetStatus = e.detail.value ? 0 : 1;
    const targetStatusText = targetStatus === 0 ? '营业' : '休息';
    const currentStatusText = targetStatus === 0 ? '休息' : '营业';

    wx.showModal({
      title: '切换营业状态',
      content: `当前状态：${currentStatusText}\n确认切换为：${targetStatusText}？`,
      confirmText: '确认切换',
      confirmColor: '#5cb85c',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '更新中...',
            mask: true
          });

          try {
            // 调用商家状态更新API（与个人中心和门店管理统一）
            const response = await MerchantAPI.updateMerchantStatus(targetStatus);
            
            if (response.code === 200) {
              wx.hideLoading();
              
              const statusText = targetStatus === 0 ? '营业中' : '休息中';
              
              wx.showToast({
                title: `已切换为${statusText}`,
                icon: 'success',
                duration: 2000
              });

              // 更新本地数据
              this.setData({
                businessStatus: targetStatus,
                statusText: statusText,
                'userInfo.status': targetStatus,
                'userInfo.statusText': statusText,
                'userInfo.canOperate': targetStatus === 0
              });

              // 更新缓存
              const cachedInfo = wx.getStorageSync('merchantUserInfo') || {};
              cachedInfo.status = targetStatus;
              cachedInfo.statusText = statusText;
              cachedInfo.canOperate = targetStatus === 0;
              wx.setStorageSync('merchantUserInfo', cachedInfo);
            } else {
              wx.hideLoading();
              wx.showToast({
                title: response.msg || '切换失败',
                icon: 'none'
              });
              // 恢复开关状态
              this.setData({
                businessStatus: !e.detail.value ? 0 : 1
              });
            }
          } catch (error) {
            console.error('切换营业状态失败:', error);
            wx.hideLoading();
            wx.showToast({
              title: '切换失败，请重试',
              icon: 'none'
            });
            // 恢复开关状态
            this.setData({
              businessStatus: !e.detail.value ? 0 : 1
            });
          }
        } else {
          // 用户取消，恢复开关状态
          this.setData({
            businessStatus: !e.detail.value ? 0 : 1
          });
        }
      },
      fail: () => {
        // 恢复开关状态
        this.setData({
          businessStatus: !e.detail.value ? 0 : 1
        });
      }
    });
  },

  /**
   * 切换自动接单状态
   */
  async toggleAutoAccept(e: any) {
    const mode = e.detail.value ? 'auto' : 'manual';
    
    try {
      // 调用API更新接单方式：/merchant/store/order-mode
      // await ShopAPI.updateOrderMode(mode);
      
      const modeText = mode === 'auto' ? '自动接单' : '手动接单';
      this.setData({ 
        acceptOrderMode: mode,
        modeText 
      });
      
      wx.showToast({
        title: modeText + '已开启',
        icon: 'success'
      });
      
    } catch (error) {
      console.error('更新接单方式失败', error);
      
      // API调用失败时仍更新本地状态
      const modeText = mode === 'auto' ? '自动接单' : '手动接单';
      this.setData({ 
        acceptOrderMode: mode,
        modeText 
      });
      
      wx.showToast({
        title: modeText + '已开启',
        icon: 'success'
      });
    }
  },

  /**
   * 导航到功能页面
   */
  navigateToAction(e: any) {
    const actionId = e.currentTarget.dataset.id;
    
    const actionMap: Record<string, string> = {
      store_management: '/pages/store/store',
      announcement_management: '/pages/announcement/announcement',
      product_management: '/pages/products/products',
      combo_management: '/pages/combos/combos',
      review_management: '/pages/reviews/reviews',
      custom_management: '/pages/custom/custom',
      activity_management: '/pages/activities/activities',
      region_bindings: '/pages/region-bindings/region-bindings'
    };
    
    const url = actionMap[actionId];
    if (url) {
      wx.navigateTo({
        url
      });
    } else {
      wx.showToast({
        title: '功能开发中',
        icon: 'none'
      });
    }
  },

  /**
   * 导航到页面
   */
  navigateTo(e: any) {
    const url = e.currentTarget.dataset.url;
    
    // 检查是否是tabBar页面
    const tabBarPages = [
      '/pages/orders/orders',
      '/pages/messages/messages',
      '/pages/workplace/workplace',
      '/pages/profile/profile'
    ];
    
    if (tabBarPages.includes(url)) {
      wx.switchTab({
        url
      });
    } else {
      wx.navigateTo({
        url
      });
    }
  },

  // 查看销售趋势详情
  viewSalesTrend() {
    wx.showToast({
      title: '销售趋势详情功能开发中',
      icon: 'none'
    });
  },

  // 刷新数据
  onRefresh() {
    if (this.data.hasLogin) {
      this.loadWorkbenchData();
    }
  }
});
